package model

import (
	"database/sql"
	"fmt"
	"github.com/doujunyu/gogo/sql_aid"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql" //mysql数据库
	_ "github.com/lib/pq"              //pg数据库
	"os"
	"time"
)

var MySql *sql.DB
var PgSql *sql.DB
var SelfRedis *redis.Client


func MySqlLine() error {
	db, err := sql.Open("mysql", os.Getenv("MYSQL_URL"))
	if err != nil {
		return err
	}
	if err := db.Ping();err != nil {
		return err
	}
	MySql = db
	MySql.SetConnMaxLifetime(time.Minute * 3)
	MySql.SetMaxOpenConns(10)
	MySql.SetMaxIdleConns(10)
	return nil
}

func PgSqlLine() error {
	db, err := sql_aid.Open("postgres", os.Getenv("PGSQL_URL"))
	if err != nil {
		return err
	}
	if err := db.Ping();err != nil {
		return err
	}
	PgSql = db
	PgSql.SetConnMaxLifetime(time.Minute * 3)
	PgSql.SetMaxOpenConns(10)
	PgSql.SetMaxIdleConns(10)
	return nil
}

func RedisLine() error {
	redisLine := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%v:%v",os.Getenv("REDIS_HOST"),os.Getenv("REDIS_PORT")),
		Password: os.Getenv("REDIS_PASSWORD"),
		DB:       1,
	})
	_, err := redisLine.Ping().Result()
	if err != nil {
		return err
	}
	SelfRedis = redisLine
	return nil
}

//func RedisLinedemo() error {
	//RedisHost := os.Getenv("REDIS_HOST")
	//RedisPort := os.Getenv("REDIS_PORT")
	//RedisPassword := os.Getenv("REDIS_PASSWORD")
	//RedisSelect := os.Getenv("REDIS_SELECT")
	//redisLine, err := redis.Dial("tcp", RedisHost+":"+RedisPort)
	//if err != nil {
	//	return err
	//}
	//if RedisPassword != "" {
	//	_, err = redisLine.Do("auth", RedisPassword)
	//	if err != nil {
	//		_ = redisLine.Close()
	//		return err
	//	}
	//}
	//_, err = redisLine.Do("select", RedisSelect)
	//if err != nil {
	//	_ = redisLine.Close()
	//	return err
	//}
	//
	//SelfRedis = redisLine
	//
	//return nil
//}



